package cn.edu.tju.se.auth.service.impl;

import cn.edu.tju.se.auth.repository.UserRepository;
import cn.edu.tju.se.auth.enity.Group;
import cn.edu.tju.se.auth.enity.Password;
import cn.edu.tju.se.auth.enity.Udr;
import cn.edu.tju.se.auth.enity.User;
import cn.edu.tju.se.auth.service.UdrService;
import cn.edu.tju.se.auth.service.UserService;
import cn.edu.tju.se.security.JwtTokenUtil;
import cn.edu.tju.se.security.JwtUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
public class UserServiceImpl implements UserService {
    
    private AuthenticationManager authenticationManager;
    private UserDetailsService userDetailsService;
    private JwtTokenUtil jwtTokenUtil;
    private UserRepository userRepository;
    @Autowired UdrService UdrService;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Value("${jwt.supercode}")
    private String supercode;
    
    @Autowired
    public UserServiceImpl(
            AuthenticationManager authenticationManager,
            UserDetailsService userDetailsService,
            JwtTokenUtil jwtTokenUtil,
            UserRepository userRepository) {
        this.authenticationManager = authenticationManager;
        this.userDetailsService = userDetailsService;
        this.jwtTokenUtil = jwtTokenUtil;
        this.userRepository = userRepository;
    }

    @Override
    public String login(String username, String password) {
        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, password);
        // Perform the security
        final Authentication authentication = authenticationManager.authenticate(upToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);

        // Reload password post-security so we can generate token
        final UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        final String token = jwtTokenUtil.generateToken(userDetails);
        return token;
    }

    @Override
    public String refresh(String oldToken) {
        final String token = oldToken.substring(tokenHead.length());
        String username = jwtTokenUtil.getUsernameFromToken(token);
        JwtUser user = (JwtUser) userDetailsService.loadUserByUsername(username);
        if (jwtTokenUtil.canTokenBeRefreshed(token, user.getLastPasswordResetDate())){
            return jwtTokenUtil.refreshToken(token);
        }
        return null;
    }

	@Override
	public void resetPassword(Password newpass) {
		User user = userRepository.findByUsername(newpass.getUsername());
		if(user!=null) {
			BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
			if (newpass.getVerify().equals(this.supercode) || encoder.matches(newpass.getVerify(), user.getPassword()) ) {
				user.setPassword(encoder.encode(newpass.getPassword()));
				user.setLastPasswordResetDate(new Date());
				userRepository.save(user);
			}
		}		
	}

	@Override
	public User add(User user) {
        final String username = user.getUsername();
        if(userRepository.findByUsername(username)!=null) {
            return null;
        }
//        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
//        final String rawPassword = user.getPassword();
//        user.setPassword(encoder.encode(rawPassword));
//        user.setLastPasswordResetDate(new Date());
//        user.setRoles(asList("ROLE_USER"));
        return userRepository.save(user);
	}

	@Override
	public User update(User user) {
		User user1 = userRepository.findOne(user.getId());
		Set<Udr> myUdr=user1.getMyUdr();
		user.setMyUdr(myUdr);
		user.setPassword(user1.getPassword());
		User res= userRepository.save(user);
		return res;
	}

	@Override
	public void delete(Long userId) {
		User user1 = userRepository.findOne(userId);
		Set<Udr> myUdr=user1.getMyUdr();
		UdrService.deleteAll(myUdr,"user");
		userRepository.delete(userId);
	}

	@Override
	public User findByUsername(String username) {
		// TODO Auto-generated method stub
		return userRepository.findByUsername(username);
	}

	@Override
	public User findByPhone(String phone) {
		// TODO Auto-generated method stub
		return userRepository.findByPhone(phone);
	}

	@Override
	public User findByEmail(String email) {
		// TODO Auto-generated method stub
		return userRepository.findByEmail(email);
	}

	@Override
	public User findOne(Long id) {
		// TODO Auto-generated method stub
		return userRepository.findOne(id);
	}

	@Override
	public List<User> findAll() {
		// TODO Auto-generated method stub
		return userRepository.findAll();
	}

	@Override
	public User lock(Long id) {
		User user = userRepository.findOne(id);
		user.setAccountNonLocked(!user.isAccountNonLocked());
		userRepository.save(user);
		return user;
	}

	@Override
	public Page<User> findAll(Pageable pageable) {
		return userRepository.findAll(pageable);
	}

	@Override
	public List<User> findWorkersOf(List<Group> groups) {
		return userRepository.findByPrimaryGroupIn(groups);
	}
	
	
}
